<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>dynamic components</title>
  <script src="/js/vue.min.js"></script>
  <style>
    .tab-button {
      padding: 6px 10px;
      border-top-left-radius: 3px;
      border-top-right-radius: 3px;
      border: 1px solid #ccc;
      cursor: pointer;
      background: #f0f0f0;
      margin-bottom: -1px;
      margin-right: -1px;
    }

    .tab-button:hover {
      background: #e0e0e0;
    }

    .tab-button.active {
      background: #e0e0e0;
    }

    .tab {
      border: 1px solid #ccc;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div id="dynamic-component-demo" class="demo">
    <h2>动态组件</h2>
    <!-- 动态渲染三个按钮, 点击时 currentTab赋值为tab -->
    <!-- currentTab === tab生效, active也会因此变为true值, 而生效被渲染为class  -->
    <button v-for="tab in tabs" v-bind:key="tab" v-bind:class="['tab-button', { active: currentTab === tab }]"
      v-on:click="currentTab = tab">
      {{ tab }}
    </button>

    <!-- 此处绑定计算属性currentTabComponent, 因为上方点击按钮会改变currentTab的值 -->
    <!-- 因此计算属性也会经函作用后返回新的值, 此处组件is属性绑定了值currentTabComponent-->
    <!-- 因此currentTabComponent变化的话, 组件也会跟着变化 -->
    <component v-bind:is="currentTabComponent" class="tab"></component>
  </div>
</body>

<script>
  Vue.component('tab-home', {
    template: '<div>Home component</div>'
  })
  Vue.component('tab-posts', {
    template: '<div>Posts component</div>'
  })
  Vue.component('tab-archive', {
    template: '<div>Archive component</div>'
  })

  let app = new Vue({
    el: '#dynamic-component-demo',
    data: {
      currentTab: 'Home',
      tabs: ['Home', 'Posts', 'Archive']
    },
    computed: {
      currentTabComponent: function () {
        return 'tab-' + this.currentTab.toLowerCase()
      }
    }
  })
</script>

</html>
